<template>
  <div class="table-info" v-loading="loading">
    <dynamic-table ref='table' :table-data="tableData" :table-header="tableList" :statics="statics" :formId="formId"
      :isInput="isInput" :initUuidList="initUuids" @selectedData="selectedData" @reloadReport="reloadReport"></dynamic-table>
    <!-- <el-button @click="postTable">提交</el-button> -->
    <div class="toolbox" v-if="!isFinish">
      <el-button @click="addTableItem" v-if="preview && type === '多行'" type="text" size="mini" icon="el-icon-plus">添加</el-button>
      <el-button @click="delTableItem" v-if="preview && selectionRecord.length" type="text" size="mini" icon="el-icon-delete">删除</el-button>
    </div>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import DynamicTable from '@/components/DynamicTable'
  import {
    getTable,
    postTableReport,
    getTableRecord   // 临时取消
  } from '@/api/question'
  import {
    getStatistFile
  } from '@/api/work'
  import {
    groupBy
  } from '@/utils/index.js'

  export default {
    name: "TableInfo",
    components: {
      DynamicTable
    },
    props: {
      statics: {
        type: Boolean,
        default: false
      },
      preview: {
        type: Boolean,
        default: false
      },
      taskId: {
        required: true
      },
      isInput: {
        type: Boolean,
        default: true
      },
      isFinish: {
        type: Boolean,
        default: false
      },
      initTableHeader:{
        type: Object,
        default(){
          return {}
        }
      }
      
    },
    data() {
      return {
        tableList: [], // 表头字段
        tableData: [],  // 表格数据
        selectionRecord: [], // 表格选中行数据
        initUuids: [], // 填充数据保存所有uuid
        type: '',
        formId: null,
        title: '',
        loading: false,
        param: [],
      }
    },
    computed: {
      ...mapGetters([
          'id'
      ])
    },
    mounted() {
      // 判断是否是数据统计
      if (this.statics) {
        this.requestStaticsFile()
      } else {
        this.requestTableById()
      }
    },
    methods: {
      // 表格填充成功后重新请求记录
      reloadReport(){
        // 临时取消重新请求记录
        // this.tableData = []
        // this.requestRecord()
      },
      // 请求表格头部信息
      requestTableById() {
        // getTable({
        //   task: this.taskId
        // }).then(res => {
          const { id, title, type, item} = this.initTableHeader
          this.type = type
          this.title = title
          this.formId = id
          this.tableList = this.handTableHeader(item)
          this.tableData = this.handTableData(item)
          if (this.preview) {
            this.requestRecord() // 查看填报记录时填充数据
          }
        // })
      },
      // 请求任务数据统计
      requestStaticsFile() {
        this.loading = true
        getStatistFile(this.taskId).then(res => {
          const data = res.data
          this.tableList = this.handTableHeader(data.formreport.item)
          this.tableData = this.formatRecordToTable(data.result, true)
          const resultUUID = Object.keys(groupBy(data.result, 'uuid'))
          this.$emit('setResultUUID', resultUUID)
          if(!data.result.length){
            this.$emit('isDataNull', true)
          }
          this.loading = false
        })
      },
      // 将填报记录数据转为表格显示数据
      formatRecordToTable(data, flag){
        const result = []
        data.forEach((item, index) =>{
          let content = {}
          item.record.forEach(e =>{
            content.index = index
            if(flag){
              content.owner = item.owner
            }
            content[e.item] = e.content
          })
          result.push(content)
        })
        return result
      },
      // 显示填报记录
      requestRecord() {
        getTableRecord({
          form: this.formId,
          owner: this.id
        }).then(res => {
          const data = res.data
          const list = this.handFilter(data)
          this.initUuids = Object.keys(list)
          if(data.length){
            this.tableData = this.formatRecordToTable(data, false)
          }
        })
      },
      handFilter(data) {
        const res = data.filter(e => e.uuid)
        return groupBy(res, 'uuid')
      },
      postTable(flag) {
        this.$refs['table'].submit(flag)
      },
      // 自定义表格多选
      selectedData(data){
        this.selectionRecord = data
      },
      addTableItem() {
        const item = this.tableData[0]
        const index = this.tableData.length + 1
        const obj = {
          index : index
        }
        Object.keys(item).forEach(e => {
          if(e !== 'index'){
            obj[e] = ''
          }
        })
        this.tableData.push(obj)

      },
      // 删除表格行记录
      delTableItem(){
        if(this.tableData.length === 1) return
        if(this.tableData.length === this.selectionRecord.length){
          this.tableData.splice(1, this.selectionRecord.length -1)
          return
        }
        this.selectionRecord.forEach(
          item =>{
            this.tableData.forEach(
              (e, index) =>{
                if(item.index === e.index){
                  this.tableData.splice(index, 1)
                }
              }
            )
          }
        )
      },
      // 初始化表格头，动态生成prop
      handTableHeader(data){
        data.forEach((item, index) => {
          item.content = ''
          item.prop = '' + item.id
          if (item.child && item.child.length) {
            this.handTableHeader(item.child)
          }
        })
        return data
      },
      // 初始化表格数据，根据prop动态生成字段名
      handTableData(data, temp = {}) {
        const result = []
        data.forEach((item, index) => {
          temp.index = index
          if(!item.child){
            temp['' + item.id] = ''
          }
          if (item.child && item.child.length) {
            this.handTableData(item.child, temp)
          }
        })
        result[0] = temp
        return result
      }
    }
  };

</script>

<style lang="scss">
  .table-info {
    .toolbox{
      margin-top: 5px;
    }
    .el-table tbody tr:hover>td {
      background-color: #fff !important
    }

    .el-table .cell,
    .el-table--border td:first-child .cell,
    .el-table--border th:first-child .cell {
      padding: 8px 6px;
      text-align: center;
    }

    .el-table tbody .cell {
      // min-height: 50px;
      // padding-top: 10px;
    }
    .el-input--small .el-input__inner {
      height: 32px;
      padding: 0;
    }

    .el-table__body td {
      padding: 0;

    }

    .el-form-item {
      margin-bottom: 12px;
    }

    .el-form-item__error {
      left: 10px;
      padding-top: 0;
    }

    .el-form-item__content {
      line-height: 18px;
    }

    margin-top: 10px;

    .el-table td,
    .el-table th.is-leaf {
      /* border-bottom: 1px solid #c7c6c6; */
      height: 24px;
    }

    /* .el-table--border:after,
      .el-table--group:after,
      .el-table:before {
          background-color: #c7c6c6;
      }

      .el-table--border,
      .el-table--group {
          border-color: #c7c6c6;
      } */

    .el-table--border,
    .el-table--group，.el-table td,
    .el-table th.is-leaf {
      /* border: none; */
    }

    /* .el-table--border th,
      .el-table--border th.gutter:last-of-type {
              border-bottom: 1px solid #c7c6c6;
      }

      .el-table--border td,
      .el-table--border th {
              border-right: 1px solid #c7c6c6;
      } */
  }

</style>
